<template>
  <q-btn
    class="my-button"
    round
    glossy
    disable
    :color="param.color"
  />
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, PropType, ref, toRefs, watch } from 'vue';
import { CVariableDataItem, CGraphEntity, CDynamicDataItem } from 'stores/editorModels';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import { CAnimationPropertyItem } from 'components/views/animation/animationViewModel';

export default defineComponent({
  name: 'ViewAnimationTwinkle',
  props: {
    detail: {
      type: Object,
      default: {} as CGraphEntity
    },
    dynamicData: {
      type: Array as PropType<CVariableDataItem[]>,
      default: () => {
        return [] as CVariableDataItem[]
      }
    }
  },

  setup (props, context) {
    // 响应数据解构
    const {
      detail,
      dynamicData
    } = toRefs(props);

    //错误通知
    const {
      showMessage
    } = useMessageNotify();

    //响应数据
    let param = ref<CAnimationPropertyItem>({
      color: 'primary'
    });

    //数据部分
    let xyData = ref<CDynamicDataItem[]>([]);

    //索引值
    let timer: any = null;
    let colorIndex = ref(0);
    let colorAry = [
      'primary',
      'teal',
      'orange',
      'info'
    ]

    //动画播放判断
    const startAnimation = () => {
      if (colorIndex.value >= colorAry.length) {
        colorIndex.value = 0;
      }

      //动态修改颜色值
      param.value.color = colorAry[colorIndex.value];
    }

    //属性更新
    const configProperty = () => {
      //个性化属性
      if ((detail.value) && (detail.value?.propsItem) &&
        (detail.value?.propsItem.length > 0)) {
        let i = 0;
        param.value.color = detail.value.propsItem[i++].value;
      } else {
        showMessage('AnimationTwinkle属性设定值不符！');
        return;
      }

      //动画播放
      startAnimation();
    }

    //更新数据
    const refreshDynamicData = () => {
      //动态数据
      if ((dynamicData.value) && (dynamicData.value.length > 0)) {
        dynamicData.value.forEach((el, index) => {
          if (xyData.value[index].vid === el.varId) {
            xyData.value[index].value = el.vData;
          }
        });
      }
    }

    //初始化
    const init = () => {
      configProperty();
      refreshDynamicData();
    }

    //监视属性变化
    watch(() => detail, () => {
      configProperty();
    }, { deep: true });

    //监视变量变化
    watch(() => dynamicData, () => {
      refreshDynamicData();
    }, { deep: true })

    //挂载组件
    onMounted(() => {
      init();

      timer = setInterval(() => {
        colorIndex.value++;
        startAnimation();
      }, 500);
    });

    //组件卸载
    onUnmounted(() => {
      clearInterval(timer);
    });

    return {
      detail,
      param
    };
  }
});
</script>

<style lang="scss" scoped>
.my-button {
  padding: 5px;
  width: 99%;
  height: 99%;
}

</style>
